18. 详情页面异步获取数据

详情页面异步获取数据,和前面其他部分都是差不多的

src/pages/detail/index.js

1
2
3
componentDidMount(){
this.props.getDetail()
}

1
2
3
4
5
6
7
8
9
10
11
12
const mapState = (state) => ({
title: state.get('detail').get('title'),
content: state.get('detail').get('content')
})

const mapDispatch = (dispatch) => ({
getDetail(){
dispatch(actionCreators.getDetail())
}
})

export default connect(mapState, mapDispatch)(Detail);

src/pages/detail/store/actionCreators.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import axios from 'axios'
import * as constants from './constants'

const changeDetail = (title, content) => ({
type: constants.CHANGE_DETAIL,
title,
content
})

export const getDetail = () =>{
return (dispatch) => {
axios.get('api/details.json').then((res) => {
const result = res.data.data
const action = changeDetail(result.title, result.content)
dispatch(action)
})
}
}

src/pages/detail/store/reducer.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
import { fromJS } from 'immutable' 
import * as constants from './constants'

const defaultState = fromJS({
title: '',
content: ''
});

export default (state = defaultState, action ) => {
switch(action.type){
case constants.CHANGE_DETAIL:
return state.merge({
title: action.title,
content: action.content
})
default:
return state;
}
}

代码地址